<template>
    <div class="code">
        <div class="code-title">{{title}}</div>
        <div class="code-canvas">
            <qrcode-vue :value="url" :size="100"></qrcode-vue>
        </div>
        <div class="code-tip">
            <nav>说明：请您在填写问卷的时候，务必填写个人的真实信息哦！</nav>
        </div>
    </div>
</template>

<script setup>
import html2canvas from "html2canvas"
import QrcodeVue from 'qrcode.vue';
import { defineProps } from 'vue';
let { url,title } = defineProps({
    url: {
        type: String,
        default: "http://baidu.com"
    },
    title:{
        type:String,
        default:"xxx调查问卷"
    }
});
const down = () => {
    let downloadContent = document.querySelector(".code");
    html2canvas(downloadContent).then(canvas => {
        let base64Text = canvas.toDataURL('image/png');
        let blob = getBlob(base64Text); //将base64转换成blob对象
        var link = document.createElement('a');
        var href = window.URL.createObjectURL(blob);
        link.href = href;
        link.download = title+'.png'; //a标签的下载属性
        document.body.appendChild(link); // firefox需要把a添加到dom才能正确执行click
        link.click(); // 延时保证下载成功执行，否则可能下载未找到文件的问题
        setTimeout(function () {
            window.URL.revokeObjectURL(href); // 释放Url对象
            document.body.removeChild(link);
        }, 100);
    })
}

let getBlob = (base64) => {
    var mimeString = base64.split(',')[0].split(':')[1].split(';')[0]; // mime类型
    var byteString = atob(base64.split(',')[1]); //base64 解码
    var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
    var intArray = new Uint8Array(arrayBuffer); //创建视图
    for (var i = 0; i < byteString.length; i += 1) {
        intArray[i] = byteString.charCodeAt(i);
    }
    return new Blob([intArray], {
        type: mimeString,
    });
}

defineExpose({
    down
})
</script>

<style scoped>
.code {
    width: 200px;
    height: auto;
    margin: 0px auto;
    text-align: center;
}

.code-canvas {
    width: 100px;
    height: 100px;
    margin: 14px auto 12px;
    padding: 20px;
    background-image: url('./Group 74.png');
    background-repeat: no-repeat;
    background-size: 100%;
    box-sizing: content-box;
}

.code-title {
    font-size: 16px;
    height: 16px;
    color: #3B8CE9;
    line-height: 16px;
    font-weight: 600;
}

.code-tip {
    line-height: 18px;
    font-size: 12px;
    color: rgba(153, 153, 153, 1);
}
</style>